<template>
	<!--新增对话框-->
	<el-dialog
		:title="editForm.id ? '编辑' : '新增'"
		:visible.sync="dialogVisible"
		width="800px"
		:before-close="handleClose"
		:destroy-on-close="true"
	>
		<el-form :model="editForm" :rules="editFormRules" ref="editForm">
			<el-form-item label="企业名称" prop="name" label-width="140px">
				<el-input v-model="editForm.name" autocomplete="off"></el-input>
			</el-form-item>
			<el-form-item label="企业类型" prop="company_type" label-width="140px">
				<el-select v-model="editForm.company_type" placeholder="企业类型" clearable>
					<el-option label="造船企业" value="1"></el-option>
					<el-option label="配套企业" value="2"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="公司图片" prop="logo" label-width="140px">
				<el-upload
				class="upload-demo"
				drag
				:action="actionUrl"
				:headers="actionHeaders"
				:with-credentials="true"
				:on-success="okHandler"
				:on-error="errorHandler"
				:show-file-list="true"
				>
					<img v-if="editForm.logoUrl" :src="editForm.logoUrl" class="avatar">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
			</el-form-item>
			<div v-for="item in editForm.metrics">
				<el-form-item :label="`${item.name}数量`" prop="logo" label-width="140px">
					<el-input v-model="item.amountValue" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item :label="`${item.name}百分比`" prop="logo" label-width="140px">
					<el-input v-model="item.percentage" autocomplete="off"></el-input>
				</el-form-item>
			</div>
			<el-form-item label="产品结构" prop="itemHierarchy" label-width="140px">
				<el-input v-model="editForm.itemHierarchy" autocomplete="off"></el-input>
			</el-form-item>
			<div v-for="(item,index) in editForm.awards">
				<el-form-item :label="`荣誉名称`" prop="itemHierarchy" label-width="140px">
					<el-input v-model="item.awardName" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item :label="`荣誉图片`" prop="imageNameUrl" label-width="140px">
					<el-upload
					class="upload-demo"
					drag
					:action="actionUrl"
					:headers="actionHeaders"
					:with-credentials="true"
					:on-success="(res) => okAwardHandler(index, res)"
					:on-error="(res) => errorAwardHandler(index, res)"
					:show-file-list="true"
					:fileList="item.fileList"
					>
					<img v-if="item.imageNameUrl" :src="item.imageNameUrl" class="avatar">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
 				<el-button type="danger" icon="el-icon-delete" size="mini" plain @click="removeAward(index)">删除该荣誉</el-button>
			</div>
			<div style="text-align: center;margin-bottom: 10px;">
				<el-button type="primary" icon="el-icon-plus"  @click="addAwards">增加荣誉</el-button>
			</div>
			<el-form-item label="省市" prop="provinceOptions" label-width="140px">
				<el-cascader
				size="large"
				:options="provinceAndCityData"
				v-model="editForm.provinceOptions">
				</el-cascader>
			</el-form-item>
			<el-form-item label="地图图片" prop="addressPic" label-width="140px">
				<el-upload
				class="upload-demo"
				drag
				:action="actionUrl"
				:headers="actionHeaders"
				:with-credentials="true"
				:on-success="okAddressHandler"
				:on-error="errorHandler"
				:show-file-list="true"
				>
					<img v-if="editForm.addressPicUrl" :src="editForm.addressPicUrl" class="avatar">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
			</el-form-item>
			<el-form-item label="报告年份" prop="report_date" label-width="140px">
                <el-date-picker
                    v-model="editForm.report_date"
                    type="year"
        			value-format="yyyy"
                    placeholder="选择年份">
                </el-date-picker>
			</el-form-item>
			<el-form-item label="备注" prop="remark" label-width="140px">
				<el-input v-model="editForm.remark" autocomplete="off"></el-input>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="resetForm('editForm')">取 消</el-button>
			<el-button type="primary" @click="submitForm('editForm')">确 定</el-button>
		</div>
	</el-dialog>
</template>

<script>
import { provinceAndCityData } from 'element-china-area-data';
import {formatServerDate} from '@/utils/date';
import { isNumber, isArray } from '@/utils/validate';
import { getApiPre, getResourceUrl } from '@/utils/index';
import TypeIdSelect from '@/components/typeIdSelect/Index.vue';
import NameIdSelect from '@/components/nameIdSelect/Index.vue';
export default {
	name: 'AddUpdateShare',
	components: {
		TypeIdSelect,
		NameIdSelect,
	},
	data() {
		return {
			editForm: {
        		provinceOptions: []
			},
            actionUrl: `${getApiPre()}/admin/boat/upload`,
            actionHeaders:  {
                Authorization: localStorage.getItem('token'), // 请求头带上token
            },
			loading: false,
			dialogVisible: false,
			editFormRules: {
				reportDate: [{ required: true, message: '请选择报告年月', trigger: 'blur' }],
				companyName: [{ required: true, message: '请输入企业数量', trigger: 'blur' }],
			},
			// -1 表示当前没有上传的图片
			uploadingImageIndex: -1,
			provinceAndCityData,
		};
	},
	mounted() {
		// this.getFarmList('');
	},

	methods: {
		resetForm(formName) {
			this.$refs[formName].resetFields();
			this.dialogVisible = false;
			this.editForm = {};
		},
		handleClose() {
			this.resetForm('editForm');
		},
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {

                    const {report_date, awards, metrics, provinceOptions,district_code,addressPic, addressPicUrl,  ...rest} = this.editForm;

					let districtCode = '';
					if(provinceOptions.length > 0 && provinceOptions[0] && provinceOptions[1]){
						districtCode = provinceOptions[1] + '00';
					}
					districtCode = districtCode.substring(0, 6);
					const awardsData = awards.map((item) => {
						return {
							award_name: item.awardName,
							image_name: item.imageName,
						}
					});
					const metricsData = (metrics || []).map((item) => {
						return {
							amount_value: item.amountValue,
							name: item.name,
							percentage: item.percentage,
						}
					});
					this.$axios
						.post('/admin/boat/yellow/company/' + (this.editForm.id ? 'edit' : 'edit'), 
                            {
                                report_date, 
								awards: awardsData,
								metrics: metricsData,
								district_code: districtCode,
								address_pic_url: addressPic,
                                ...rest,
                        },)
						.then((res) => {
							this.$message({
								showClose: true,
								message: '恭喜你，操作成功',
								type: 'success',
								onClose: () => {
									this.$emit('refreshDataList');
								},
							});
							this.dialogVisible = false;
							this.resetForm(formName);
						}).catch(e => {
							this.$message({
								type: 'warning',
								message: '对不起，请稍后再试',
							});
						});
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		checkIsDisabledDate(date){
			console.log(date);
			return true;
		},
		init(id) {
			this.dialogVisible = true;
			if (id != null && id != '' && id > 0) {
				this.$axios.get('/admin/boat/yellow/company/detail?id=' + id).then((res) => {
                    const {result = {}} = res;
                    const { awards, logo,address_pic_url, district_code, ...rest} = result;

					let provinceOptions = [];
					if(district_code){
						provinceOptions[0] = district_code.substring(0, 2);
						provinceOptions[1] = district_code.substring(0, 4);
					}

					const editFormData = {
                        id: id,
						awards: (awards || []).map((item) => {
							const {imageName, } = item;
							return {
								district_code,
								imageNameUrl: getResourceUrl(imageName),
								...item,
							}
						}),
						logo,
						logoUrl: getResourceUrl(logo),

						district_code,
						provinceOptions,
						...rest,

					}

					if(address_pic_url){
						editFormData.addressPic = address_pic_url;
						editFormData.addressPicUrl = getResourceUrl(address_pic_url);
					}


                    this.editForm = editFormData;
				});
			}
		},
        okHandler(res){
			this.$message({
				type: res.success ? 'success' : 'warning',
				message: res.message
			});
            if(res.success){
				this.editForm.logo = res.result.file_name;
				this.editForm.logoUrl = getResourceUrl(res.result.file_name);
            }
		},
		okAddressHandler(res){
			this.$message({
				type: res.success ? 'success' : 'warning',
				message: res.message
			});
            if(res.success){
				this.editForm.addressPic = res.result.file_name;
				this.editForm.addressPicUrl = getResourceUrl(res.result.file_name);
            }

		},
        errorHandler(err){
            this.$message({
                type: 'warning',
                message: '对不起，请稍后再试',
            });
        },
        okAwardHandler(index, res){
			this.$message({
				type: res.success ? 'success' : 'warning',
				message: res.message
			});
            if(res.success){
				this.editForm.awards[index].imageName = res.result.file_name;
				this.editForm.awards[index].imageNameUrl = getResourceUrl(res.result.file_name);
            }
		},
        errorAwardHandler(index, err){
            this.$message({
                type: 'warning',
                message: '对不起，请稍后再试',
            });
        },
		addAwards(){
			if(!(this.editForm.awards)){
				this.editForm.awards = [];
			}
			this.editForm.awards.push({
				awardName: '',
				imageName: '',
				fileList: [],
			});
		},
		removeAward(index){
			this.editForm.awards.splice(index, 1);
		},
		onImageChangeAward(index){
			console.log(index)
		}
	},
};
</script>

<style scoped>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}
.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
